//
//  MapTool.m
//
//  Created by 王江华 on 16/8/26.
//  Copyright © 2016年 SRDZ.com. All rights reserved.
//

#import "MapTool.h"
#import "ChangeLocation.h"
#import "Header.h"
const double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
@interface MapTool()<CLLocationManagerDelegate>

@property (strong, nonatomic) CLLocationManager* locationManager;
@property (strong, nonatomic) NSString *currentCity;

@end


@implementation MapTool
+ (MapTool *)sharedMapTool {
    static MapTool *mapTool = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        mapTool = [[self alloc] init];
        [mapTool openGpsLocation];
    });
    return mapTool;
}


- (NSString *)getLocationCity{
    
    return self.gps_cityName;
}
- (NSString *)getSubLocation {
    
    
    return self.gps_detailCityName;
}


- (void)openGpsLocation {
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0)
        {
            //设置定位权限 仅ios8有意义
            [self.locationManager requestWhenInUseAuthorization];// 前台定位
        }
        self.locationManager.delegate = self;
        //设置定位的精度
        self.locationManager.distanceFilter = 100.f;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [self.locationManager requestWhenInUseAuthorization];
        }
        [self.locationManager startUpdatingLocation];
    } else {
        [[NSUserDefaults standardUserDefaults] setValue:@"杭州" forKey:MW_CITY];
        
        self.gps_longitude = @"120.0";
        self.gps_latitude = @"30.0";
        [[NSUserDefaults standardUserDefaults] setValue:self.gps_latitude forKey:MW_LAT];
        [[NSUserDefaults standardUserDefaults] setValue:self.gps_longitude forKey:MW_LOG];
    }

}


#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
   // [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleFade];
   // [MMProgressHUD showWithTitle:@"正在获取当前位置"];
  /*  NSError *error;
    if (!newLocation) {
        [self locationManager:manager didFailWithError:error];
        return;
    }
    
    if (signbit(newLocation.horizontalAccuracy)) {
        [self locationManager:manager didFailWithError:error];
        return;
    }
    //定位完成后就停止定位
    //CLLocationCoordinate2D coor2D = [ChangeLocation wgs84ToGcj02:newLocation.coordinate];
    self.gps_longitude = [NSString stringWithFormat:@"%.6f",coor2D.longitude];
    self.gps_latitude = [NSString stringWithFormat:@"%.6f",coor2D.latitude];
   // DLog(@"%f %f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
    [[NSUserDefaults standardUserDefaults] setValue:self.gps_latitude forKey:MW_LAT];
    [[NSUserDefaults standardUserDefaults] setValue:self.gps_longitude forKey:MW_LOG];
    
    [manager stopUpdatingLocation];
    //获取当前所在城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error)
     {
         //联网情况下才能定位出城市名字
         if (placemarks.count > 0) {
             CLPlacemark *placemark = [placemarks objectAtIndex:0];
             self.gps_detailCityName = placemark.subLocality;
          //   self.gps_detailCityName = [NSString stringWithString:[self.gps_detailCityName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
             
             DLog(@"%@",self.gps_detailCityName);//具体位置
             DLog(@"thoroughfare,%@",placemark.thoroughfare);       // 街道
             DLog(@"subThoroughfare,%@",placemark.subThoroughfare); // 子街道
             DLog(@"locality,%@",placemark.locality);// 市
             
             DLog(@"subLocality,%@",placemark.subLocality);         // 区
             DLog(@"country,%@",placemark.country);                 // 国家
             //获取城市
             NSString *city = placemark.locality;
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 city = placemark.administrativeArea;
             }
             self.gps_cityName = city;
             [[NSUserDefaults standardUserDefaults] setValue:placemark.locality forKey:MW_CITY];
             
             if ([[UserManager sharedHelper] checkHasUser] && city.length > 0 && ![city isEqualToString:@"(null)"] && placemark.subLocality.length > 0) {
                // User *user = [[UserManager sharedHelper] inquireUser];
                // [[RequestHelper shareHelper] uploadLocationInfoWithUserId:user.userId lat:self.gps_latitude log:self.gps_longitude city:self.gps_cityName locationDesc:placemark.subLocality Block:^(id data) {
                     if ([data[@"status"] integerValue] == 1) {
                       //  DLog(@"更新位置信息成功");
                     }
                 }];
             }
             self.isSuccess = YES;
             
         } else if (error == nil && [placemarks count] == 0){
             self.isSuccess = YES;
             //DLog(@"没有匹配到对应的城市");
         }else if (error != nil){
             self.isSuccess = YES;
            // DLog(@"Error reason:%@", error);
           
         }
     }];*/
}


+ (NSString *)getFiterWithLatitude:(float)latitude longitude:(float)longitude
{
    NSString *currentLongitude = [[NSUserDefaults standardUserDefaults] valueForKey:MW_LOG];
    NSString *currentLatitude = [[NSUserDefaults standardUserDefaults] valueForKey:MW_LAT];
    CLLocation *cllo = [[CLLocation alloc] initWithLatitude:[currentLatitude floatValue] longitude:[currentLongitude floatValue]];
    CLLocation *nowLoc = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    CLLocationDistance dis = [cllo distanceFromLocation:nowLoc];
   // DLog(@"%f",dis);
    NSString *str;
    if (dis >= 1000) {
        str = [NSString stringWithFormat:@"%.0f km",dis/1000];
    }else{
        str = [NSString stringWithFormat:@"%.0f m",dis];
    }
    return str;
}





@end
